package com.atguigu.guli.service.sms.service.impl;

import com.aliyun.api.gateway.demo.util.HttpUtils;
import com.atguigu.guli.common.base.result.R;
import com.atguigu.guli.common.base.result.ResultCodeEnum;
import com.atguigu.guli.service.base.exception.GuliException;
import com.atguigu.guli.service.sms.service.SmsService;
import com.atguigu.guli.service.sms.util.SmsProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class SmsServiceImpl implements SmsService {
    @Override
    public R send( String phoneNum ,String code) {

        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + SmsProperties.APPCODE);
        Map<String, String> querys = new HashMap<String, String>();

        // 生成验证码
        /*StringBuilder builder = new StringBuilder();
        for(int i = 0; i < 4; i++){
            int random = (int)(Math.random()*10);
            builder.append(random);
        }
        String code = builder.toString();*/

        querys.put("content", "【儿童教务】您正在登录验证,验证码为"+code+" ,60s内有效,请尽快验证。");
        // 接收验证码的手机号
        querys.put("mobile", phoneNum);


        try {
            HttpResponse response = HttpUtils.doGet(SmsProperties.HOST, SmsProperties.PATH, SmsProperties.METHOD, headers, querys);
            StatusLine statusLine = response.getStatusLine();
            // 状态码：200正常；400URL无效，401Code错误；403次数用完；500API网管错误
            int statusCode = statusLine.getStatusCode();

            String reasonPhrase = statusLine.getReasonPhrase();
            if(statusCode == 200){
                // 成功返回验证码
                return R.ok().message("短信发送成功");
            }

            return R.error().message(reasonPhrase);
            //System.out.println(response.toString());
            // 状态码：200正常；400URL无效，401Code错误；403次数用完；500API网管错误
            //获取response的body
            // System.out.println(EntityUtils.toString(response.getEntity()));
            //logger.info(EntityUtils.toString(response.getEntity()));
        } catch (Exception e) {
            log.error("短信发送失败!"+e.getMessage());

            throw new GuliException(ResultCodeEnum.SMS_SEND_ERROR);
           /* return R.error().message(e.getMessage());*/

        }
    }
}
